<?php

/**
 * @name NovelController
 * @ 小说控制器
 */
class NovelController extends BaseController {

    private $_novelSvc;
    private $_userSvc;
    
    public function init ()
    {
        parent::init ();
        $this->_novelSvc = new Service_NovelModel();
        $this->_userSvc  = new Service_UserModel();
    }
    
    //小说详情
    public function novelInfoAction()
    {
        $novelid = $this->_params->getNovelId();
        $param = array ( 'novel_id' => $novelid );
        $uid = $this->checkLogin();
        $record = $this->getRecord();
        $data = $this->_novelSvc->getNovelInfo( $param , $uid , $record );
        $data['recommend'] = $this->_novelSvc->getChannelList( array ( 'r_cate_id' => 1 ) );
        if($data && !empty($data)){
            $this->getView ()->assign ( 'data' , $data );
            $this->getView ()->display ( 'novel/read_info.html' );
        }else{
            echo parent::des_encode_msg(Tools_Response::Error([],'系统繁忙请稍后再试'));
        }
    }
    
    //小说列表
    public function listsAction() 
    {        
        $data = $this->_novelSvc->getList();
        if($data && !empty($data)){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
        }else{
            echo parent::des_encode_msg(Tools_Response::Error([],'系统繁忙请稍后再试'));
        }
    }
    
    //小说分类列表
    public function categoryListsAction() 
    {        
        $data = $this->_novelSvc->getCategoryList();
        if($data && !empty($data)){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
        }else{
            echo parent::des_encode_msg(Tools_Response::Error([],'系统繁忙请稍后再试'));
        }
    }
    
    //小说章节列表
    public function chapterListAction()
    {
        $novelid = $this->_params->getNovelId();
        $param = array ();
        $param['chapter_novel_id'] = $novelid;
        $param['page'] = $this->_params->getPage();
        $list = $this->_novelSvc->getChapterList($param);
        $data['list'] = $list;
        $data['cnt']  = count($list);
        if( $data ){
//            echo parent::des_encode_msg(Tools_Response::Succ($data));
            $this->getView ()->assign ( 'data' , $data );
            $this->getView ()->display ( 'novel/read_list.html' );
        }else{
            echo parent::des_encode_msg(Tools_Response::Error([],'系统繁忙请稍后再试'));
        }
    }
    
    //ajax获取章节列表
    public function ajaxGetChapterListAction()
    {
        $novelid = $this->_params->getNovelId();
        $param = array ();
        $param['chapter_novel_id'] = $novelid;
        $param['page'] = $this->_params->getPage();
        $list = $this->_novelSvc->getChapterList($param);
        rsort($list);
        $data['list'] = $list;
        $data['cnt']  = count($list);
        if( $data ){
            echo parent::des_encode_msg( Tools_Response::Succ( $data ) );
        }else{
            echo parent::des_encode_msg( Tools_Response::Error( [],'系统繁忙请稍后再试' ) );
        }
    }
    
    //小说章节内容
    public function chapterContentAction()
    {
        $novelid = $this->_params->getNovelId();
        $chapterid = $this->_params->getChapterId();
        $param = array ();
        $param['chapter_id']        = $chapterid;
        $param['chapter_novel_id']  = $novelid;
        $uid                        = $this->checkLogin();
        if($uid){
            $data['user'] = $this->_userSvc->getUserInfo($uid); 
        }else{
            $this->addVisitor();
            $data['user'] = []; 
        }
        $record = $this->getRecord();
        $data['novelInfo']          = $this->_novelSvc->getNovelInfo( array('novel_id'=>$novelid) , $uid , $record );
//        var_dump($data['novelInfo'] );exit();
        $data['set']                = $this->_userSvc->getUserSet( $uid ? $uid : 0 );
        $data['in_case']            = $this->_novelSvc->checkInCase( $novelid , $uid );
//        $data['progress']           = $this->_novelSvc->getNextChapter( $param );
        $data['menu']               = $this->_novelSvc->getChapterList( $param );
        $data['progress']           = $this->getNextChapter($data['menu'], $param);
        $content                    = $this->_novelSvc->getChapterContent( $param );
        $data['content']            = $content['content'];
        $data['need_pay']           = $content['need_pay'];
        if( $data['content'] != '<p>获取内容失败</p>' && $data['content'] != '<p>小说不存在</p>'){
            $this->addRecord( $novelid , $chapterid );
        }
        $data['novel_id'] = $novelid;
        $data['chapter_id'] = $chapterid;
//        dump($data['menu'][$chapterid-1]['chapter_name']);exit();
        $this->getView ()->assign ( 'data' , $data );
        $this->getView ()->display ( 'novel/pageInfo.html' );
    }
    
    private function getNextChapter($list,$params)
    {
        $n = array_column ( $list , null , 'chapter_id' );
        $res['name'] = $n[$params['chapter_id']]['chapter_name'];
        $res['order'] = $n[$params['chapter_id']]['chapter_order'];
        unset($n);
        $l = array_column ( $list , 'chapter_order' , 'chapter_id' );
        $o = array_column ( $list , 'chapter_id' , 'chapter_order' );
        $order = $l[ $params['chapter_id'] ];
        if( isset($o[ $order + 1 ]) ){
            $res['down'] = $o[ $order + 1 ];
        }
        if( isset($o[ $order - 1 ]) ){
            $res['up'] = $o[ $order - 1 ];
        }
        return $res;
    }
    
    //ajax
    public function ajaxChapterContentAction()
    {
        $novelid = $this->_params->getNovelId();
        $chapterid = $this->_params->getChapterId();
        $param = array ();
        $param['chapter_id'] = $chapterid;
        $param['chapter_novel_id'] = $novelid;
        $uid = $this->checkLogin();
        if($uid){
           $data['user'] = $this->_userSvc->getUserInfo($uid); 
        }else{
           $data['user'] = []; 
        }
        $data['progress'] = $this->_novelSvc->getNextChapter( $param );
        $content = $this->_novelSvc->getChapterContent( $param );
        $data['content'] = $content['content'];
        $data['need_pay'] = $content['need_pay'];
        $data['novel_id'] = $novelid;
        $data['chapter_id'] = $chapterid;
        if( $data['content'] != '<p>获取内容失败</p>' ){
            $this->addRecord( $novelid , $chapterid );
            echo parent::des_encode_msg( Tools_Response::Succ( $data ) );
        }else{
            echo parent::des_encode_msg( Tools_Response::Error( 1 ,'获取内容失败' ) );
        }
    }
    
    //加入书架
    public function addBookCaseAction()
    {
        if( $this->isPost() ){
            $uid = $this->checkLogin();
            if(!$uid){
                //跳登录页面
                echo parent::des_encode_msg(Tools_Response::Error(1,'请先登录'));
                exit();
//                $this->redirect('login');
            }
            $novelid = $this->_params->getNovelId();
            $res = $this->_novelSvc->addBookCase( $novelid , $uid );
            if(!isset($res['msg'])){
                echo parent::des_encode_msg(Tools_Response::Succ($res));
            }else{
                echo parent::des_encode_msg(Tools_Response::Error(1,$res['msg']));
            }
        }
    }
    
    //删除书架中的小说
    public function delBookCaseAction()
    {
        if( $this->isPost() ){
            $uid = $this->checkLogin();
            if(!$uid){
                //跳登录页面
                $this->redirect('login');
                exit();
            }
            $novelid = $this->_params->getNovelId();
            $type = $this->_params->getType();
            if($type == 1){
                $res = $this->_novelSvc->delBookCase( $novelid , $uid);
            }elseif($type == 2){
                $res = $this->delRecords( $novelid , $uid );
            }
            if($res){
                echo parent::des_encode_msg(Tools_Response::Succ($res));
            }else{
                echo parent::des_encode_msg(Tools_Response::Error(1,'删除失败'));
            }
        }
    }
    
    //ajax获取用户书架、阅读记录
    public function ajaxGetBookAction()
    {
//        $uid = $this->_params->getUserId();
        $type = $this->_params->getType();
        $records = $this->getRecord();
        if( $type == 1 ){
            $uid = $this->checkLogin();
            if(!$uid){
                $this->redirect('login');
                exit();
            }
            $res     = $this->_novelSvc->getUserBookCase( $uid , $records );
        }elseif( $type == 2 ){
            $res  = $this->_novelSvc->getUserReadRecord( $records );
        }
        if( $res ){
            echo parent::des_encode_msg( Tools_Response::Succ( $res ) );
        }else{
            echo parent::des_encode_msg( Tools_Response::Error( 1 , '获取小说失败' ) );
        }
    }
    
    //热搜
//    public function searchHotNovelAction()
//    {
//        $this->getView ()->display ( 'novel/search_hot.html' );
//    }
    
    //阅读首页
    public function novelHomePageAction()
    {
        $data = [
            'record' => [],
            'novels' => [],
        ];
        $record = $this->getRecord();
        if( $record ){
            $r = $this->_novelSvc->getUserReadRecord( $record );
            $data[ 'record' ] = $r[ 'list' ];
        }
//        $novels = $this->_novelSvc->getAllChannelList();
//        $data['novels'] = $novels;
        $data['new'] = $this->_novelSvc->getNewBookList( array( 'page' => 1 , 'pageSize' => 2 , 'orderBy' => 0 ) );
        $data['free'] = $this->_novelSvc->getNewBookList( array( 'page' => 1 , 'pageSize' => 2 ,'needPay' => 1 , 'orderBy' => 0 ) );
        $data['well_chosen'] = $this->_novelSvc->getNewBookList( array( 'page' => 1 , 'pageSize' => 2 , 'well_chosen' => 1 , 'orderBy' => 0 ) );
        $this->getView ()->assign ( 'data' , $data );
        $this->getView ()->display ( 'novel/home_page.html' );
    }
    
    //更多
    public function moreAction()
    {
        $type = $this->_params->getType();
        if( !$type ){
            $this->redirect('login');
            exit();
        }
        $data = [];
        $data['info'] = $this->_novelSvc->getChannelInfo( array ( 'cate_id' => $type ) );
        $data['novels'] = $this->_novelSvc->getChannelList( array ( 'r_cate_id' => $type , 'page' => 1 , 'limit' => 10) );
        $this->getView ()->assign ( 'data' , $data );
        $this->getView ()->display ( 'novel/more.html' );
    }
    
    //新书
    public function newBookAction()
    {
        $page       = $this->_params->getPage();
        $orderBy    = $this->_params->getOrderBy();
        $isFinish   = $this->_params->getIsFinish();
        $wordCount  = $this->_params->getWordCount();
        $needPay    = $this->_params->getNeedPay();
        $from       = $this->_params->getFrom();
        $params     = [
            'page'      => $page ? $page : 1,
            'pageSize'  => 10,
            'orderBy'   => $orderBy,
            'isFinish'  => $isFinish,
            'wordCount' => $wordCount,
            'needPay'   => $needPay,
            'from'      => $from,
        ];
        $data['list'] = $this->_novelSvc->getNewBookList( $params );
        $data['type'] = 'new';
        if(count($data['list']['list']) > 0){
            $params['page'] = $params['page'] + 1;
        }
        $params['pageNum'] = ceil($data['list']['total']/10);
        $data['params'] = $params;
        if($this->isPost()){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
            exit();
        }
//        var_dump($data['list']);exit();
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/newBook.html' );
    }
    
    //新书
    public function chosenBookAction()
    {
        $page       = $this->_params->getPage();
        $orderBy    = $this->_params->getOrderBy();
        $isFinish   = $this->_params->getIsFinish();
        $wordCount  = $this->_params->getWordCount();
        $needPay    = $this->_params->getNeedPay();
        $from       = $this->_params->getFrom();
        $params     = [
            'page'        => $page ? $page : 1,
            'pageSize'    => 10,
            'orderBy'     => $orderBy,
            'isFinish'    => $isFinish,
            'wordCount'   => $wordCount,
            'needPay'     => $needPay,
            'well_chosen' => 1,
            'from'        => $from,
        ];
        $data['list'] = $this->_novelSvc->getNewBookList( $params );
        $data['type'] = 'chosen';
        if(count($data['list']['list']) > 0){
            $params['page'] = $params['page'] + 1;
        }
        $params['pageNum'] = ceil($data['list']['total']/10);
        $data['params'] = $params;
        if($this->isPost()){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
            exit();
        }
//        var_dump($data['list']);exit();
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/newBook.html' );
    }
    
    //免费
    public function freeBookAction()
    {
        $page       = $this->_params->getPage();
        $orderBy    = $this->_params->getOrderBy();
        $isFinish   = $this->_params->getIsFinish();
        $wordCount  = $this->_params->getWordCount();
        $from       = $this->_params->getFrom();
        $params     = [
            'page'      => $page ? $page : 1,
            'pageSize'  => 10,
            'orderBy'   => $orderBy,
            'isFinish'  => $isFinish,
            'wordCount' => $wordCount,
            'needPay'   => 1,
            'from'       => $from
        ];
        $data['list'] = $this->_novelSvc->getNewBookList( $params );
        $data['type'] = 'free';
        if(count($data['list']['list']) > 0){
            $params['page'] = $params['page'] + 1;
        }
        $params['pageNum'] = ceil($data['list']['total']/10);
        $data['params'] = $params;
        if($this->isPost()){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
            exit();
        }
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/newBook.html' );
    }
    
    //排行
    public function RankBookAction()
    {
        $data['hotSell'] = $this->_novelSvc->getHotSaleList( 1 , 1 , 5 );
        $data['newBook'] = $this->_novelSvc->getNewBookList( array( 'page' => 1 , 'pageSize' => 5, 'orderBy' => 4 ) , 1 ); 
        $data['click']   = $this->_novelSvc->getClickBookList( 1 , 5 );
        $data['lianzai'] = $this->_novelSvc->getTypeBookList( 1 , 5 , 2 );
        $data['wanjie']  = $this->_novelSvc->getTypeBookList( 1 , 5 , 1 );
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/rankBook.html' );
    }
    
    //热销榜
    public function HotSaleRankAction()
    {
        $page = $this->_params->getPage();
        $type = $this->_params->getType();
        $data['list'] = $this->_novelSvc->getHotSaleList( $type , $page ? $page : 1 , 10 );
        $data['type'] = "hot";
        $data['daily_type'] = $type;
        $params = [
            'page' => $page ? $page : 1,
            'type' => $type,
        ];
        if(count($data['list']['list']) > 0){
            $params['page'] = $params['page'] + 1;
        }
        $params['pageNum'] = ceil($data['list']['total']/10);
        $data['params'] = $params;
        if($this->isPost()){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
            exit();
        }
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/billboard.html' );
    }
    
    /**
     * 新书榜
     */
    public function NewBookRankAction()
    {
        $page = $this->_params->getPage();
        $type = $this->_params->getType();
        $data['list'] = $this->_novelSvc->getNewBookList( array( 'page' => $page ? $page : 1 , 'pageSize' => 10, 'orderBy' => 4 ) , $type );
        $data['type'] = "new";
        $data['daily_type'] = $type;
        $params = [
            'page' => $page ? $page : 1,
            'type' => $type,
        ];
        if(count($data['list']['list']) > 0){
            $params['page'] = $params['page'] + 1;
        }
        $params['pageNum'] = ceil($data['list']['total']/10);
        $data['params'] = $params;
        if($this->isPost()){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
            exit();
        }
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/billboard.html' );
    }
    
    /**
     * 点击榜
     */
    public function ClickRankAction()
    {
        $page = $this->_params->getPage();
        $type = $this->_params->getType();
        $data['list'] = $this->_novelSvc->getClickBookList( $page ? $page : 1 , 10 , $type );
        $data['type'] = "click";
        $data['daily_type'] = $type;
        $params = [
            'page' => $page ? $page : 1,
            'type' => $type,
        ];
        if(count($data['list']['list']) > 0){
            $params['page'] = $params['page'] + 1;
        }
        $params['pageNum'] = ceil($data['list']['total']/10);
        $data['params'] = $params;
        if($this->isPost()){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
            exit();
        }
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/billboard.html' );
    }
    
    /**
     * 完本连载榜
     */
    public function BookTypeRankAction()
    {
        $page = $this->_params->getPage();
        $type = $this->_params->getType();
        $isFinish = $this->_params->getIsFinish();
        $data['list'] = $this->_novelSvc->getTypeBookList( $page ? $page : 1 , 10 , $isFinish , $type );
        $data['type'] = "continue";
        if($isFinish == 1){
            $data['type'] = "all";
        }
        $data['daily_type'] = $type;
        $params = [
            'page' => $page ? $page : 1,
            'type' => $type,
        ];
        if(count($data['list']['list']) > 0){
            $params['page'] = $params['page'] + 1;
        }
        $params['pageNum'] = ceil($data['list']['total']/10);
        $data['params'] = $params;
        if($this->isPost()){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
            exit();
        }
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/billboard.html' );
    }
    
    /**
     * 分类
     */
    public function categoryAction()
    {
        $ctype = $this->_params->getCtype();
        $from       = $this->_params->getFrom();
        if(!$ctype){
            $data = [];
            $data['params']['from'] = $from;
            $this->getView()->assign( 'data' , $data );
            $this->getView()->display( 'novel/classifty.html' );
            exit();
        }
        $page       = $this->_params->getPage();
        $orderBy    = $this->_params->getOrderBy();
        $isFinish   = $this->_params->getIsFinish();
        $wordCount  = $this->_params->getWordCount();
        $needPay    = $this->_params->getNeedPay();
        $params     = [
            'page'      => $page ? $page : 1,
            'pageSize'  => 10,
            'orderBy'   => $orderBy,
            'isFinish'  => $isFinish,
            'wordCount' => $wordCount,
            'needPay'   => $needPay,
            'category'  => $ctype,
            'from'      => $from
        ];
        $data['list'] = $this->_novelSvc->getNewBookList( $params );
        $data['info'] = $this->_novelSvc->getCategoryInfo( $ctype );
        $data['type'] = 'category';
        if(count($data['list']['list']) > 0){
            $params['page'] = $params['page'] + 1;
        }
        $params['pageNum'] = ceil($data['list']['total']/10);
        $data['params'] = $params;
        if($this->isPost()){
            echo parent::des_encode_msg(Tools_Response::Succ($data));
            exit();
        }
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/newBook.html' );
    }
    
    /**
     * 搜索
     */
    public function searchAction()
    {
        $a = $this->_params->getA();
        $action = '';
        if($a == 'home'){
            $action = 'novelHomePage';
        }
        $data['params']['act'] = $action;
        if($this->isPost()){
            $keyword  = $this->_params->getKeyword();
            $page     = $this->_params->getPage();
            $orderBy  = $this->_params->getOrderBy();
            $pageSize = $this->_params->getPageSize();
            $params     = [
                'page'      => $page ? $page : 1,
                'pageSize'  => $pageSize,
                'orderBy'   => $orderBy,
                'kw'        => $keyword,
            ];
            $data['list']  = $this->_novelSvc->getByKeyword( $keyword , $page , $orderBy , $pageSize );
            if(count($data['list']['list']) > 0){
                $params['page'] = $params['page'] + 1;
            }
            $params['pageNum'] = ceil($data['list']['total']/10);
            $data['params'] = $params;
            echo parent::des_encode_msg(Tools_Response::Succ($data));
            exit();
        }
        $this->getView()->assign( 'data' , $data );
        $this->getView()->display( 'novel/search_hot.html' );
    }

    //ajax获取banner轮播图
    public function ajaxGetBannerListAction()
    {
        $list = $this->_novelSvc->getBannerList();
        rsort($list);
        $data['list'] = $list;
        $data['cnt']  = count($list);
        if( $data ){
            echo parent::des_encode_msg( Tools_Response::Succ( $data ) );
        }else{
            echo parent::des_encode_msg( Tools_Response::Error( [],'系统繁忙请稍后再试' ) );
        }
    }
    
    
    //订阅章节
    public function chargeAction(){
        if($this->isPost()){
            $uid = $this->checkLogin();
            if(!$uid){
                //跳登录页面
                $this->redirect('login');
                exit();
            }
            $novelid = $this->_params->getNovelId();
            $chapterid = $this->_params->getChapterId();
            //获取该用户当前小说消费记录
//            $novelid = 1;
//            $chapterid = 35;
            $list = $this->_userSvc->getUserNovelConsume($uid,$novelid,$chapterid);
            if(!empty($list)){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_CHAPTER_HAS_PAYED, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_CHAPTER_HAS_PAYED)) );
                exit();
            }
            //如果该章没有付费，查一下付费的价格
            $info =  $this->_novelSvc->getChapterInfo($chapterid);
            if(empty($info)){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_CHAPTER_NOT_EXIST, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_CHAPTER_NOT_EXIST)) );
                exit();
            }
            //用户扣钱，加消费记录
            $res = $this->_novelSvc->payChapter($uid,$novelid,$chapterid,$info['charge_price']);
            if($res){
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_SUCCESS, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_SUCCESS)) );
                exit();
            }else{
                echo parent::des_encode_msg( Tools_Response::ErrorEcho(ErrorCodeTool::ERROR_CHAPTER_PAY_FAILED, ErrorCodeTool::getMsg(ErrorCodeTool::ERROR_CHAPTER_PAY_FAILED)) );
                exit();
            }
        }
    }
}
